#####################################################################
# Results robustness checks 
#####################################################################

rm(list=ls())

library(lmtest)
library(sandwich)
library(stargazer)

# load function that does clustered SEs
vcovCluster <- function(
  model,
  cluster
)
{
  require(sandwich)
  require(lmtest)
  if(nrow(model.matrix(model))!=length(cluster)){
    stop("check your data: cluster variable has different N than model")
  }
  M <- length(unique(cluster))
  N <- length(cluster)           
  K <- model$rank   
  if(M<40){
    warning("Fewer than 40 clusters, variances may be unreliable")
  }
  dfc <- (M/(M - 1)) * ((N - 1)/(N - K))
  uj  <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum));
  rcse.cov <- dfc * sandwich(model, meat = crossprod(uj)/N)
  return(rcse.cov)
}

##############################################
# Read data and prepare basic output
##############################################

# Generate log  
#sink("007_outcome_rob_check.txt")

# Read data
load("004_rob_check_ego.Rdata")

d_ego = d
d_match_ego = d_match
d = NULL
d_match = NULL

# Read data 
load("005_rob_check_socio.Rdata")

d_socio = d
d_match_socio = d_match
d = NULL
d_match = NULL

##########################
# Regressions results
##########################

# Ego: treatment + control
mod1a = lm(outcome ~ t_ind_ego + 
                     v22c_presvote + 
                     v41e_thermserra_imp + 
                     v50_ideology_imp, 
                     data=d_match_ego)

# Socio: treatment + control
mod2a = lm(outcome ~ t_ind_socio + 
                     v22c_presvote + 
                     v41e_thermserra_imp + 
                     v50_ideology_imp, 
                     data=d_match_socio)

# TABLE 2 APPENDIX
stargazer(mod1a,mod2a,
          type = "text",
          title="Robustness check egotropic and sociotropic treatment",
          align=TRUE, 
          omit.stat=c("LL","ser","f","rsq","adj.rsq"), 
          no.space=TRUE,  
          multicolumn = TRUE,
          table.placement = "H",
          #single.row = TRUE,
          #column.separate = c(4,4),
          covariate.labels=c("Negative egotropic treatment","Negative sociotropic treatment"),
          dep.var.caption  = "Voting for the incumbent",
          dep.var.labels.include = FALSE,
          omit = c("v22c_presvote","v41e_thermserra_imp","v50_ideology_imp","bairroibge","Constant"),
          add.lines = list(c("Controls","Yes","Yes"),
                           c("Neighborhood Fixed effects","No","No")))

# Equivalence test 
z_ego =  (-.101 - -0.099) / sqrt(.042^2 + 0.087^2)
z_ego 

z_socio =  (.011 - 0.032) / sqrt(.038^2 + 0.050^2)
z_socio
  
#sink()
  